from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.views.generic import View
import os,datetime,json
###
from mydemo2.handle_excel.handle_excel import HandleExcel


# Create your views here.


class My_handle(View):

    def get(self,request):
        return render(request,'mydemo2/index.html',{})

    def post(self,request):
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        print(BASE_DIR)
        if request:
            file_object=request.FILES.get('upfile') #获取前端上传的文件
            print('file name is {}'.format(file_object.name))
            #创建保存路径
            path=os.path.join(BASE_DIR,'mydemo2/db/{}'.format(file_object.name))
            path=path.replace('\\','/')
            print('save path is{}'.format(path))
            if os.path.exists(path):
                #如果文件存在 就不处理。。
               return HttpResponse(" file already exists!")
            else:
                f=open(path,'wb+')
                #分段把文件写入到路径中
                for chunk in file_object.chunks():
                    f.write(chunk)
                f.close()
                return HttpResponse("file save ok!!!")


class MyTableData(View):
    def __init__(self):
        self.default_row = 10  # 默认显示的行数
        self.default_page = 1  # 默显示第一页

    def get(self,request):
        page_namber = request.GET.get('page')  # 获取前端传过来的page
        if page_namber:
            self.default_page = page_namber

        han = HandleExcel()  # 实例化处理Excel的类
        excel_data = han.get_excel_data(self.default_row,self.default_page)
        # print(excel_data)
        return HttpResponse(json.dumps(excel_data))





